package DAO;

import java.awt.event.*;
import java.sql.*;
import javax.swing.*;
import Main.DBMain;

public class DelCourse extends JFrame {
	private JPanel contentPane = new JPanel();
	private JLabel lab_Tip;
	private JTextField tf_Course;
	private JButton btn_OK, btn_Exit;
	String course = null;
	boolean result = false;

	public DelCourse() {
		setTitle("删除科目");
		setSize(300, 200);
		setLocationRelativeTo(null);
		setContentPane(contentPane);
		contentPane.setLayout(null);

		lab_Tip = new JLabel("请输入要删除的科目：");
		lab_Tip.setBounds(20, 20, 130, 30);
		contentPane.add(lab_Tip);

		tf_Course = new JTextField(15);
		tf_Course.setBounds(165, 22, 100, 25);
		tf_Course.addKeyListener(new KeyAdapter() {
			// 添加回车监听，点击回车，直接进行操作
			public void keyPressed(KeyEvent e) {
				if (e.getKeyCode() == KeyEvent.VK_ENTER) {
					delTea();
					if (result) {
						delCourse(course);
						JOptionPane.showMessageDialog(null, "删除成功！");
						setVisible(false);
					} else {
						JOptionPane.showMessageDialog(null, "删除失败！");
					}
				}
			}
		});
		contentPane.add(tf_Course);

		btn_OK = new JButton("确定");
		btn_OK.setBounds(60, 80, 70, 40);
		btn_OK.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				// 添加按钮监听，点击按钮进行操作
				delTea();
				if (result) {
					delCourse(course);
					JOptionPane.showMessageDialog(null, "删除成功！");
					setVisible(false);
				} else {
					JOptionPane.showMessageDialog(null, "删除失败！");
				}
			}
		});
		contentPane.add(btn_OK);

		btn_Exit = new JButton("取消");
		btn_Exit.setBounds(160, 80, 70, 40);
		btn_Exit.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				setVisible(false);
			}
		});
		contentPane.add(btn_Exit);

		setVisible(true);
	}

	// 从学生表中删除所有学生该科目成绩
	public void delCourse(String sub) {
		Connection conn2 = null;
		Statement stmt = null;
		String sql = "ALTER TABLE stu_info DROP `" + sub + "` "; // 删除字段语句
		try {
			conn2 = DBMain.getConnection();
			stmt = conn2.createStatement();
			stmt.executeUpdate(sql);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	// 从教师表中删除该科目教师
	public void delTea() {
		Connection conn1 = null;
		PreparedStatement pstmt1 = null;
		course = tf_Course.getText().trim();
		if (!("".equals(course))) {
			try {
				conn1 = DBMain.getConnection();
				String sql1 = "delete from tea_info where teaCourse = ?"; // 删除教师信息
				pstmt1 = conn1.prepareStatement(sql1);
				pstmt1.setString(1, course);
				int i = pstmt1.executeUpdate();
				if (i != 0) {
					result = true;// 删除成功
				} else {
					result = false;
					JOptionPane.showMessageDialog(null, "该科目不存在！");
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		} else {
			JOptionPane.showMessageDialog(null, "请输入要删除的科目！");
		}
	}
}
